package com.jh.paymentchannel.service;


import java.net.URI;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.util.Util;
import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;
@Service
public class KjTopupPage implements TopupRequest{
	private static final Logger log = LoggerFactory.getLogger(KjTopupPage.class);
	
	@Autowired
	Util util;
	@Value("${kuaijie.req_url}")
	private String req_url;

	@Value("${kuaijie.merchant_key}")
	private String merchant_key;

	@Value("${kuaijie.merchant_no}")
	private String merchant_no;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	public static final Set<String> base64Key = new HashSet<String>();
	static {
		base64Key.add("subject");
		base64Key.add("body");
		base64Key.add("remark");
		base64Key.add("customerInfo");
		base64Key.add("accResv");
		base64Key.add("riskRateInfo");
		base64Key.add("billpQueryInfo");
		base64Key.add("billDetailInfo");
		base64Key.add("respMsg");
		base64Key.add("resv");
	}
	
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request,
			String amount, String ordercode, String orderdesc, String extra,
			String notifyurl, String returnurl, String channelParam)
			throws Exception {
		/**根据订单号获取相应的订单*/
		String bankcard =null;//信用卡卡号
		String expiredTime = null;//付款信用卡有效期,格式YYMM
		String securityCode = null;//付款信用卡安全码
		String phone = null;//预留信用卡手机号码
		String lineNo = null;//联行行号
		String idcardJJ = null;//借记卡账户身份证号
		String idcard = null;//身份证号
		String bankName = null;//信用卡银行名
		String userNameJJ = null;//借记卡用户姓名
		String userName = null;//信用卡用户姓名
		long userid = 0;//用户ID
		String bankNameJJ = null;//借记卡银行名
		String cardNo = null;//借记卡卡号
		String lineNoJJ = null;//借记卡联行行号
		String telphone = null;//借记卡预留手机号
		String priOrPub = null;//对私还是对公帐户
		String priOrPubJJ = null;
		String bankBranchName = null;//开户支行名称
		String desc = null;//显示页面描述
		String brandname = null;//商品名称,用于显示在支付界面 
		String province = null;
		String city = null;
		//String rate ;//结算费率(实体类型为BigDecimal)
		String channelid = null;
		
		Map maps = new HashMap();
		{
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		JSONObject resultObj = null;
		try {
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/transactionclear/payment/query/ordercode--RESULT================"+result);
			JSONObject jsonObject =  JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单有误======"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询订单信息有误");
			return maps;
		}
		bankcard =  resultObj.getString("bankcard");
		desc = resultObj.getString("desc");
		channelid = resultObj.getString("channelid");
		brandname = resultObj.getString("brandname");
		//rate = resultObj.getString("rate");
		}	
		if(bankcard == null || bankcard.equalsIgnoreCase("")){
			return null;
		}
		
		{
			/**根据订单号获取相应的订单*/
			RestTemplate restTemplate=new RestTemplate();
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/bank/default/cardno";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("cardno", bankcard);
			requestEntity.add("type", "0");
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
			JSONObject jsonObject =  JSONObject.fromObject(result);
			JSONObject resultObj  =  jsonObject.getJSONObject("result");
			if(resultObj==null){
				return null;
			}
			 expiredTime = resultObj.getString("expiredTime");//付款信用卡有效期,格式YYMM
			 securityCode = resultObj.getString("securityCode");//付款信用卡安全码
			 phone = resultObj.getString("phone"); //预留信用卡手机号码
			 lineNo = resultObj.getString("lineNo");//联行行号
			 idcard = resultObj.getString("idcard");//身份证号
			 bankName = resultObj.getString("bankName");//信用卡银行名
			 priOrPub = resultObj.getString("priOrPub");//对私还是对公帐户
			 userName = resultObj.getString("userName");//用户姓名
			 userid = resultObj.getLong("userId");//用户ID
			
			restTemplate=new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/userid";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("user_id", String.valueOf(userid));
			result = restTemplate.postForObject(url, requestEntity, String.class);
			String respCode = "";
			log.info("接口/v1.0/user/bank/default/userid--RESULT================"+result);
			try {
				jsonObject =  JSONObject.fromObject(result);
				resultObj  =  jsonObject.getJSONObject("result");
				respCode  =  jsonObject.getString("resp_code");
			} catch (Exception e) {
				log.error("查询结算卡异常" + e.getMessage());
				Map map = new HashMap();
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "没有结算卡");
				return map;
			}
			
			if(!"000000".equals(respCode)){
				Map map = new HashMap();
				map.put("resp_code", "failed");
				map.put("resp_message", "没有结算卡");
				return map;
			}
			

			province = resultObj.getString("province");
			city = resultObj.getString("city");
			bankBranchName = resultObj.getString("bankBranchName");//开户支行名称
			 bankNameJJ = resultObj.getString("bankName");//借记卡银行名
			 cardNo = resultObj.getString("cardNo");//借记卡卡号
			 lineNoJJ = resultObj.getString("lineNo");//借记卡联行行号
			 telphone = resultObj.getString("phone");//借记卡预留手机号
			 priOrPubJJ = resultObj.getString("priOrPub");
			 userNameJJ = resultObj.getString("userName");//借记卡用户姓名
			 idcardJJ = resultObj.getString("idcard");//借记卡账户身份证号
		}
		URI uri = util.getServiceUrl("user", "error url request!");
		String road = uri.toString() + "/v1.0/user/channel/rate/query/userid";
		
		/**根据的渠道标识或去渠道的相关信息*/
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channel_id", channelid);
		requestEntity.add("user_id", String.valueOf(userid));
		RestTemplate restTemplate=new RestTemplate();
		JSONObject jsonObject = null;
		try {
			String resultObjx = restTemplate.postForObject(road, requestEntity, String.class);
			log.info("接口/v1.0/user/channel/rate/query/userid--RESULT================"+resultObjx);
			jsonObject = JSONObject.fromObject(resultObjx);
		} catch (Exception e) {
			log.error("查询通道费率有误======"+e);
			maps.put(CommonConstants.RESP_CODE, "failed");
			maps.put(CommonConstants.RESP_MESSAGE, "查询通道费率有误");
			return maps;
		}
		
		Map<String,String> map = new HashMap<String,String>();
		if(!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "亲.支付失败,臣妾已经尽力了,请重试!");
			return map;
		}
		
		JSONObject resultObj  =  jsonObject.getJSONObject("result");
		String rate = resultObj.getString("rate");	
		if(Double.valueOf(rate)<0.0035) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "费率不能小于0.0035");
			return map;
		}
		Double rat = Double.parseDouble(rate)*100;
		String withdrawFee = resultObj.getString("withdrawFee");
		Double amt = Double.valueOf(amount);
		DecimalFormat df = new DecimalFormat("0.00");//格式化
		String CNY = df.format(amt);
		Map mapp = new HashMap();
		mapp.put("resp_code", "success");	
		mapp.put("channel_type", "kuaijie");
		mapp.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/kuaijie"+"?bankName="+URLEncoder.encode(bankNameJJ,"UTF-8")+"&bankBranchId="+lineNoJJ+
		"&bankNo="+cardNo+"&amount="+CNY+"&ordercode="+ordercode+"&province="+URLEncoder.encode(province,"UTF-8")+"&city="+URLEncoder.encode(city,"UTF-8")+"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+
		"&expiredTime="+expiredTime+"&securityCode="+securityCode+"&channelParam="+channelParam);
		return mapp;  
	    
	}
	
}
